var aceEditor;
var aceEditorFieldName;
var aceEditorFormName;
function initScriptCtl(formName, fieldName) {
  aceEditorFormName = formName;
  aceEditorFieldName = fieldName;
  aceEditor = ace.edit("pre_" + fieldName);
  aceEditor.setTheme("ace/theme/eclipse");
  // aceEditor.setTheme("ace/theme/terminal");
  aceEditor.getSession().setMode("ace/mode/java");

  aceEditor.on("blur", aceBlurListener);
    
  setTimeout(function() {
    aceEditor.setOptions({
      readOnly: false,
      highlightActiveLine: true,
      highlightGutterLine: true
    })
  }, 500);

  // 会使得光标不显示
  // aceEditor.renderer.$cursorLayer.element.style.opacity=0;   
  aceEditor.setValue($(fo(fieldName)).val());	
}

function aceBlurListener() {
	// console.log('aceBlurListener', aceEditor.getValue());
	fo(aceEditorFieldName).value = aceEditor.getValue();
}

// ajaxForm序列化提交数据之前的回调函数，注释掉是因为通过aceBlurListener可以给字段赋值
// function ctlOnBeforeSerialize(formName) {
// 	// 当其它表单调用本方法时，为防止存在同名字段而被aceEditor赋值
// 	if (aceEditorFormName != formName)
// 		return;
// 	console.log('ctlOnBeforeSerialize fo(aceEditorFieldName, formName)', fo(aceEditorFieldName, formName));
// 	// ajaxForm提交前，必须先提取赋值
// 	if (fo(aceEditorFieldName, formName)) {
// 		$(fo(aceEditorFieldName, formName)).val(aceEditor.getValue());
// 	}
// }

function getScript() {
	return aceEditor.getValue();
}

function setScript(script) {
	aceEditor.setValue(script);
}

// var ideUrl = "<%=url%>";
var ideWin;
var cwsToken = "";

function openIdeWin() {
	// ideWin = openWinMax(ideUrl);
	openScriptDesigner(getScript());
}

var onMessage = function(e) {
	var d = e.data;
	var data = d.data;
	var type = d.type;
	if (type=="setScript") {
		setScript(data);
		if (d.cwsToken!=null) {
			cwsToken = d.cwsToken;
			// ideUrl = "<%=request.getContextPath()%>/admin/script_frame.jsp?cwsToken=" + cwsToken;
		}
	}
	else if (type=="getScript") {
		var data={
		    "type":"openerScript",
		    // "version":"<%=version%>",
		    // "spVersion":"<%=spVersion%>",
		    "scene": "ScriptCtl",		    
		    "data":getScript()
	    }
		ideWin.leftFrame.postMessage(data, '*');
	} else if (type == "setCwsToken") {
    	cwsToken = d.cwsToken;
		// ideUrl = "<%=request.getContextPath()%>/admin/script_frame.jsp?cwsToken=" + cwsToken;
	}
}